package app.jfinal;

import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.druid.DruidPlugin;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Config {
    @Value("${spring.datasource.url}")
    protected String dbUrl;
    @Value("${spring.datasource.username:any}")
    protected String username;
    @Value("${spring.datasource.password:any}")
    protected String password;

    /* use SPEL expressions */
    @Value("${db.initialSize:2}")
    protected int initialSize;
    @Value("${db.minIdle:1}")
    protected int minIdle;//最小连接池数量
    @Value("${db.maxActive:5}")
    protected int maxActive;
    protected DruidPlugin druid;

    @Autowired
    public void initDB() {
        System.out.println("初始化数据源....");
        druid = new DruidPlugin(dbUrl, username, password);
        druid.setInitialSize(initialSize);
        druid.setMinIdle(minIdle);
        druid.setMaxActive(maxActive);
        druid.start();
        System.out.println("数据源初始化完成！");
        System.out.println("初始化 Active Record....");
        initActiveRecordPlugin(dbUrl, druid).start();
        System.out.println("Active Record 初始化完成！");
    }

    protected ActiveRecordPlugin initActiveRecordPlugin(String dsName, String dbUrl, DruidPlugin druid) {
        ActiveRecordPlugin arp = new ActiveRecordPlugin(dsName, druid);
        arp.setDialect(new MysqlDialect());
        addMappings(arp);
        return arp;
    }

    protected ActiveRecordPlugin initActiveRecordPlugin(String dbUrl, DruidPlugin druid) {
        String dsName = RandomStringUtils.randomAlphabetic(10);
        return initActiveRecordPlugin(dsName, dbUrl, druid);
    }

    /**
     * 添加映射关系
     * @param arp
     */
    protected  void addMappings(ActiveRecordPlugin arp){
           arp.addMapping("city", City.class);
    }
}